const express = require("express");
const { Message, UserJoin, UserList } = require("../models/chat");

const router = express.Router();
// 获取聊天记录
router.get("/history", async (req, res) => {
  const { username, myName } = req.query;
  try {
    const messages = await Message.find({
      $or: [
        { from: username, to: myName },
        { from: myName, to: username },
      ],
    });
    res.status(200).json({ code: 0, data: messages });
  } catch (error) {
    res.status(500).json({ message: "Error fetching messages" });
  }
});

// 好友列表
router.get("/userList", async (req, res) => {
  const { myName } = req.query;
  try {
    let userJoinList = await UserJoin.find({
      is: true,
      $or: [{ user1: myName }, { user2: myName }],
    }).exec();

    let newUserJoinList = [];

    for (let userJoin of userJoinList) {
      let otherUserName =
        userJoin.user1 !== myName ? userJoin.user1 : userJoin.user2;

      // 在 userList 集合中查找 otherUserName 相同的记录
      let userListRecord = await UserList.findOne({
        username: otherUserName,
      }).exec();

      if (userListRecord) {
        newUserJoinList.push({
          userJoin,
          socketId: userListRecord ? userListRecord.id : null,
        });
      }
    }
    let newUserJoinListWithSocketId = newUserJoinList.map((item) => {
      return {
        ...item.userJoin.toObject(), // 将 userJoin 转为普通对象
        socketId: item.socketId ? item.socketId : null, // 确保正确获取到 socketId
      };
    });
    res.status(200).json({ code: 0, data: newUserJoinListWithSocketId });
  } catch (error) {
    console.log(error);

    res.status(500).json({ messag: "服务器出错，为查询到数据" });
  }
});

// 添加好友请求
router.get("/addUserJoin", async (req, res) => {
  const { addUserNameVal, myName } = req.query;
  try {
    let userJoin = await UserJoin.findOne({
      $or: [
        { $and: [{ user1: addUserNameVal }, { user2: myName }] },
        { $and: [{ user1: myName }, { user2: addUserNameVal }] },
      ],
    }).exec();

    if (userJoin) {
      res.status(200).json({ code: 0, message: "对方暂未同意!" });
    } else {
      let userInfo = await UserList.findOne({
        username: addUserNameVal,
      }).exec();
      let noMyjoinMy = addUserNameVal === myName;

      if (!userInfo || noMyjoinMy) {
        res.status(200).json({ code: 10, message: "用户不存在!" });
      } else {
        const newUserJoin = new UserJoin({
          user1: addUserNameVal,
          user2: myName,
          lastmsg: null,
          msgtime: null,
          is: false,
          to: null,
        });
        await newUserJoin.save();
        res.status(200).json({ code: 0, message: "发送请求成功!" });
      }
    }
  } catch (error) {
    res.status(500).json({ message: "添加失败!" });
  }
});

// 获取好友请求列表
router.get("/addUserList", async (req, res) => {
  const { myName } = req.query;
  try {
    let userJoinList = await UserJoin.find({ user1: myName, is: false }).exec();

    res.status(200).json({ code: 0, data: userJoinList });
  } catch (error) {
    res.status(500).json({ message: "获取好友请求列表失败!" });
  }
});

// 是否同意好友请求
router.get("/isAddUser", async (req, res) => {
  const { myName, addUserName, is } = req.query;
  if (is === "true") {
    try {
      let updatedUserJoin = await UserJoin.findOneAndUpdate(
        { user1: myName, user2: addUserName, is: false },
        { is: true },
        { new: true }
      ).exec();

      if (updatedUserJoin) {
        res.status(200).json({ code: 0, message: "同意好友请求!" });
      } else {
        res.status(200).json({ code: 0, message: "好友请求不存在!" });
      }
    } catch (error) {
      res.status(500).json({ message: "同意请求失败!" });
    }
  } else {
    try {
      let deletedUserJoin = await UserJoin.findOneAndDelete({
        user1: myName,
        user2: addUserName,
        is: false,
      }).exec();

      if (deletedUserJoin) {
        res.status(200).json({ code: 0, message: "拒绝好友请求!" });
      } else {
        res.status(200).json({ code: 0, message: "好友请求不存在!" });
      }
    } catch (error) {
      res.status(500).json({ message: "拒绝请求失败!" });
    }
  }
});

// 消息已读
router.get("/isread", async (req, res) => {
  const { myName, toName } = req.query;
  try {
    await UserJoin.findOneAndUpdate(
      {
        $or: [
          { user1: myName, user2: toName },
          { user1: toName, user2: myName },
        ],
      },
      {
        $set: {
          isread: 0,
        },
      },
      { new: true } // 设置为true表示返回更新后的数据
    ).exec();

    res.status(200).json({ code: 0, message: "已读" });
  } catch (error) {
    res.status(500).json({ message: "获取好友请求列表失败!" });
  }
});

module.exports = router;
